package org.i_plus.controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.i_plus.model.ChatBean;
import org.i_plus.model.services.ChatService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.google.gson.Gson;

public class ChatRefreshServlet extends HttpServlet {
	private ChatService service;	
	@Override
	public void init() throws ServletException {
		WebApplicationContext context =
				WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
		this.service = (ChatService)context.getBean("ChatService");
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String fromacc = req.getParameter("fromacc");
		String toacc = req.getParameter("toacc");
		String page = req.getParameter("page");
		
		List<ChatBean> beans = service.select(fromacc, toacc, Integer.parseInt(page));
			
//		JSONArray result = new JSONArray();		
//		for(ChatBean temp:beans){
//			org.json.simple.JSONObject json = new JSONObject();
//			json.put("fromacc", temp.getC_fromacc());
//			json.put("toacc", temp.getC_toacc());
//			json.put("content", temp.getC_content());
//			json.put("time", temp.getC_time().toString());
//			json.put("situation", temp.getC_situation());
//			result.add(json);
//		}
		
		Gson gson = new Gson();
		String result = gson.toJson(beans);
		
		resp.setCharacterEncoding("UTF-8");
		resp.getWriter().print(result);
		return;
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doGet(req, resp);
	}
	
}
